const router = require('express').Router()
const validateToken = require('../../../common/validateToken')
const status_code = require('../../../common/status_code')
const db = require('../../../db/async-db')
const { to } = require('await-to-js')
const Bee = require('../../../common/bee/bee')

router.get('/get-child-menu', async (req, resp) => {
  // 错误处理
  function handleError(errCode, error) {
    resp.json({
      code: errCode,
      msg: status_code[errCode],
    })
    console.error(error)
  }
  const { sqltype, id } = req.query
  if (
    !Bee.StringUtils.isNotBlank(sqltype) ||
    !Bee.StringUtils.isNumber(parseInt(id))
  )
    return handleError(10003, '参数错误')

  // sqltype: 0 = 只查找启用的菜单  1 = 只查找隐藏的菜单  2 = 查找全部菜单
  let sql = ''
  if (Bee.StringUtils.getStrLast(sqltype, 1) === '0') {
    sql = 'SELECT * FROM menu WHERE menu_status = 0 AND parent_id = ?'
  } else if (Bee.StringUtils.getStrLast(sqltype, 1) === '1') {
    sql = 'SELECT * FROM menu WHERE menu_status = 1 AND parent_id = ?'
  } else if (Bee.StringUtils.getStrLast(sqltype, 1) === '2') {
    sql = 'SELECT * FROM menu WHERE parent_id = ?'
  } else {
    return handleError(10003, '参数错误')
  }

  const [getMenuError, getMenuSuccess] = await to(db.query(sql, [parseInt(id)]))
  if (getMenuError || !getMenuSuccess) return handleError(-1, getMenuError)
  return resp.json({
    code: 0,
    msg: status_code[0],
    data: getMenuSuccess,
  })
})

module.exports = router
